﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Unity;

namespace Arch.Common.IoC
{
    public class ArchUnityServiceLocator : ServiceLocatorImplBase, IDisposable
    {
        private IUnityContainer _container;
        public IUnityContainer Container
        {
            get { return _container; }
            protected set { _container = value; }
        }

        public ArchUnityServiceLocator(IUnityContainer container)
        {
            this._container = container;
            container.RegisterInstance<IServiceLocator>(this, new ExternallyControlledLifetimeManager());
        }

        //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1816:CallGCSuppressFinalizeCorrectly",
        //    Justification = "Object is not finalizable, no reason to call SuppressFinalize")]
        public void Dispose()
        {
            if (_container != null)
            {
                _container.Dispose();
                _container = null;
            }
        }

        protected override object DoGetInstance(Type serviceType, string key)
        {
            if (_container == null) throw new ObjectDisposedException("container");
            return _container.Resolve(serviceType, key);
        }

        protected override IEnumerable<object> DoGetAllInstances(Type serviceType)
        {
            if (_container == null) throw new ObjectDisposedException("container");
            return _container.ResolveAll(serviceType);
        }
    }
}
